# 使用文本文件存储token

import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)

def get_user_dict():
    info_dict = {}
    # 使用 db.txt 而不是 字典存储,优势有很多: 不用重启服务
    with open("db.txt", mode="r",encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            token, name = line.split(",")
            info_dict[token] = name
        return info_dict


@app.route("/bili", methods=["POST"])
def bili_sign():
    """
    请求的URL中需要携带 token:
    request data form {"ordered_string"}
    """
    token = request.args.get("token")
    if not token:
        return jsonify({"status":False, "data":"认证失败"})

    user_dict = get_user_dict()
    print(f"user_dict: {user_dict}")

    """
    key in d 其实和 key in d.keys()是一样的效果, 不过建议优先使用前者, 因为它的效率更高
    """
    # if token not in user_dict.keys():
    if token not in user_dict :
        return jsonify({"status":False, "data":"认证失败"})

    try:
        ordered_string = request.json.get("ordered_string")
        if not ordered_string:
            return jsonify({"status":False,"data":"参数错误"})

        encrypt_string = ordered_string + "560c52ccd288fed045859ed18bffd9773"
        obj = hashlib.md5(encrypt_string.encode("utf-8"))
        sign = obj.hexdigest()
        return jsonify({"status": True, "data": sign})
    except:
        return jsonify({"status": False, "data": "未知错误"})


if __name__ == "__main__":
    app.run()
